package org.chaos.sekiro.workorder.app.form.internal.dao

import org.chaos.sekiro.common.ktorm.AuditTable
import org.chaos.sekiro.workorder.app.form.internal.model.ComponentBindAttribute
import org.ktorm.database.Database
import org.ktorm.dsl.and
import org.ktorm.dsl.eq
import org.ktorm.dsl.inList
import org.ktorm.entity.*
import org.ktorm.schema.long
import org.ktorm.schema.varchar
import org.springframework.stereotype.Repository
import java.time.LocalDateTime

object ComponentBindAttributes : AuditTable<ComponentBindAttribute>("wo_component_bind_attributes") {
    val id = long("id").primaryKey().bindTo { it.id }
    val userId = long("user_id").bindTo { it.userId }
    val formId = long("form_id").bindTo { it.formId }
    val componentId = long("component_id").bindTo { it.componentId }
    val attributeId = long("attribute_id").bindTo { it.attributeId }
    val value = varchar("value").bindTo { it.value }
}

val Database.componentBindAttributes get() = this.sequenceOf(ComponentBindAttributes)

@Repository
class ComponentBindAttributeDao(
    private val database: Database
) {

    fun findByUserIdAndFormIdAndComponentIdIn(
        userId: Long,
        formId: Long,
        componentIds: List<Long>
    ): List<ComponentBindAttribute> = database.componentBindAttributes.filter {
        (it.userId eq userId) and
                (it.formId eq formId) and
                (it.componentId inList componentIds)
    }.toList()

    fun insert(entities: List<ComponentBindAttribute>) {
        entities.forEach {
            it.createdTime = LocalDateTime.now()
            it.modifiedTime = LocalDateTime.now()
            database.componentBindAttributes.add(it)
        }
    }

    fun update(entities: List<ComponentBindAttribute>) {
        entities.forEach {
            it.modifiedTime = LocalDateTime.now()
            database.componentBindAttributes.update(it)
        }
    }

    fun deleteByUserIdAndFormIdAndComponentIdAndAttributeId(
        userId: Long,
        formId: Long,
        componentId: Long,
        attributeId: Long
    ) {
        database.componentBindAttributes.removeIf {
            it.userId eq userId
            it.formId eq formId
            it.componentId eq componentId
            it.attributeId eq attributeId
        }
    }
}